package com.legrand.www.module.filter;


import com.legrand.www.module.core.util.JwtToken;
import com.legrand.www.module.core.util.TokenUtil;
import com.legrand.www.module.util.RequestContextUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class MyZuulFilter extends ZuulFilter {

       private static final String FILTER_URL = "/api/**/sec/**";
       @Value("${zuul.ignored-headers}")//${eureka.client.serviceUrl.defaultZone}
       private String aa;

       @Override
       public String filterType() {
              return "pre";
       }

       @Override
       public int filterOrder() {
              return 1;
       }

       /**
        * @author xiah
        * description: 判断接口是否需要登录认证
        * param:
        * return:
        * date: 2018/5/2
        */
       @Override
       public boolean shouldFilter() {

              RequestContext ctx = RequestContext.getCurrentContext();
              HttpServletRequest request = ctx.getRequest();
           return request.getRequestURL().toString().toLowerCase().contains(FILTER_URL);
       }

       /**
        * @author xiah
        * description: 如果需要登录认证就调用run方法
        * param:
        * return:
        * date: 2018/5/2
        */
       @Override
       public Object run() {
              RequestContext ctx = RequestContext.getCurrentContext();
              HttpServletRequest request = ctx.getRequest();
              String accessToken = request.getHeader("accessToken");
              if(accessToken==null){
                     new RequestContextUtil(ctx,401,"accessToken为空!");
              }
              try {
                     if ( JwtToken.checkToken(TokenUtil.interceptToken(accessToken)) ) {
                            return null;
                     }
                     new RequestContextUtil(ctx,500,"accessToken错误!");
              } catch ( Exception e ) {
                     /*如果发生错误中断下一步请求*/
                     new RequestContextUtil(ctx,500,"accessToken错误!");
              }

              return null;
       }
}
